package com.example.studentmanager.fargment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.studentmanager.R;
import com.example.studentmanager.db.CourseManager;
import com.example.studentmanager.db.entity.Course;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CourseListFragment extends Fragment {
    private ArrayList<HashMap<String, String>> data = new ArrayList<>();
    private SimpleAdapter simpleAdapter;
    private ListView lvMain;

    public static CourseListFragment createFragment() {
        return new CourseListFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_course_list, container, false);
        initView(root);
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        List<Course> allCourse = CourseManager.findAllCourse();
        for (Course course : allCourse) {
            HashMap<String, String> map = new HashMap<>();
            map.put("name", course.getName());
            map.put("teacher", course.getTeacher());
            data.add(map);
        }
        simpleAdapter = new SimpleAdapter(getContext(), data, R.layout.item_course, new String[]{"name", "teacher"}, new int[]{R.id.tvName, R.id.tvTeacher});
        lvMain.setAdapter(simpleAdapter);
    }

    private void initView(View root) {
        lvMain = root.findViewById(R.id.lvMain);
    }
}
